
<template>
  <es-row :width="1920" :height="980" :justify-content="'space-around'">
    <div class="leftContent">
      <span class="guize-title">游戏规则</span>
      <span class="guize-content">{{guize}}</span>
    </div>
    <div class="layout">
      <es-row>
        <span class="score">步数：{{ -score }}</span>
        <text-button ref="startBtn"
          :text="isPlaying?'按返回结束':'开始游戏'"
          :color="isPlaying?'gray':'green'"
          @click="init"
                     :nextFocusName="{ up: 'navBar'}"
        ></text-button>
        <span
          class="meRank">排名：{{ meRank ? meRank.rankNum + ' (' + (-meRank.score) + '步)' : '-' }}</span>
      </es-row>
      <div class="all-container"
           :blockFocusDirections="['up','right','down','left']"
      >
        <div class="board">
          <!--棋盘-->
          <div v-for="row in 4" :key="row" class="board-row"
          >
            <div v-for="col in 4" :key="col"
                 class="board-col" >
            </div>
          </div>
          <!--棋子-->
          <qt-view v-for="item in 25" v-if="board" ref="boardItem"
                   :focusable="itemFocusable(item)"
                   :enableFocusBorder="true"
                   class="board-item" @click="placeStone(item)"
                   :style="itemStyle(item)"
                   :focusScale="1.3"
          />
        </div>
      </div>
    </div>
    <div class="ranklist">
      <s-text-view :font-size="32" text="排行榜"></s-text-view>
      <s-text-view v-for="(item,index) in rankList" :font-size="30"
                   :text="'第'+(index+1)+'名：'+(-item.score)+'步'"></s-text-view>
    </div>
  </es-row>
</template>
<script lang="ts">
import {defineComponent, nextTick, ref} from 'vue'
import EsRow from "../components/container/EsRow.vue";
import {useESEventBus, useESLog, useESToast} from "@extscreen/es3-core";
import {useESRouter} from "@extscreen/es3-router";
import {WolfAi} from "./types/WolfAi";
import {computed} from "@vue/runtime-core";
import {__CONFIG__, apiUrl} from "./config/global";
import {cached, cached2n} from "../tools/utils";

export default defineComponent({
  name: "GameView",
  components: {EsRow},
  setup(props,{emit}){
    const TAG="Index"
    var toast = useESToast();
    const router = useESRouter()
    const esLog = useESLog();
    const customerNoticeRef = ref()
    var esEventBus = useESEventBus();
    const startBtn=ref()
    const rankList = ref([])
    const meRank = ref(null)
    const board = ref([
      [0, 2, 2, 2, 0],
      [0, 0, 0, 0, 0],
      [1, 1, 1, 1, 1],
      [1, 1, 1, 1, 1],
      [1, 1, 1, 1, 1] ])
    const boardItem=ref([])
    const posSet=new Set()
    let colorMap = {
      0: 'transparent',
      1: 'white',
      2: 'black'
    }
    const wolfAi=new WolfAi()
    const score = ref(0)
    const guize='黑色棋子为狼，白色棋子为羊。\n' +
      '狼先手，羊后手。\n' +
      '狼走两格可以吃羊，\n' +
      '也可以走一格。\n' +
      '羊只能走一格。\n' +
      '目标：\n' +
      '狼将羊吃完为狼胜,\n' +
      '羊将狼困住为羊胜。'
    const isPlaying = ref(false)
    const selectList=computed(()=>{
      let moveTo=[]
      if (selectPos.value>0){
        moveTo=wolfAi.getSheepCanMoveTo(board.value,{x:toRow(selectPos.value),y:toCol(selectPos.value)})
      }
      let list=[...wolfAi.getSheepCanMovePos(board.value),
        ...moveTo]
      // console.log(list)
      return list
    })
    const selectPos=ref(0)
    function init() {
      if (isPlaying.value){
        return
      }
      initStatus()
      nextTick(()=>{
        boardItem.value[10].requestFocus()
      })
      isPlaying.value = true
      emit('gameStateChange',isPlaying.value)
      //狼先手
      board.value=wolfAi.wolfStep(board.value)
    }

    function initStatus() {
      score.value = 0
      board.value=[
        [0, 2, 2, 2, 0],
        [0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1]
      ]
      posSet.clear()
    }

    function saveScore(score) {
      if (__CONFIG__.userInfoObj &&
        __CONFIG__.userInfoObj.userId) {
        fetch(apiUrl + "/rank/save", {
          method: 'POST',
          headers: {
            "content-type": "application/json"
          },
          body: JSON.stringify({
            packageName: __CONFIG__.packageName,
            userId: __CONFIG__.userInfoObj.userId,
            score: score,
            nickName: __CONFIG__.userInfoObj.nickName
          })
        }).then(res => res.json()).then(res => {
          if (res.code == 1) {
            meRank.value = res.data
            console.log('rankSave', meRank)
          }
        })
      }

    }

    function onBackPressed() {
      startBtn.value.requestFocus()
      selectPos.value=-1
      isPlaying.value = false
    }
    function loginInit() {
      if (__CONFIG__.userInfoObj && __CONFIG__.userInfoObj.userId) {
        getMeRank()
      }
    }
    function getMeRank(){
      //获取自己排名
      fetch(apiUrl + "/rank/me?packageName=" + __CONFIG__.packageName + "&userId=" + __CONFIG__.userInfoObj.userId)
        .then(res => res.json())
        .then(res => {
          console.log('meRank', res)
          if (res.code == 1) {
            meRank.value = res.data
          }
        })
    }
    function getRankList() {
      fetch(apiUrl + "/rank/list?packageName=" + __CONFIG__.packageName, {
        method: 'GET'
      }).then(res => res.json())
        .then(res => {
          console.log('rankList', res)
          if (res.code == 1) {
            rankList.value = res.data
          }
        })
    }

    function placeStone(item) {
      //如果当前有棋子则选中
      if (1==board.value[toRow(item)][toCol(item)]){
        selectPos.value=item
      }else{
        if (selectPos.value>0) {
          board.value[toRow(selectPos.value)][toCol(selectPos.value)]=0
          board.value[toRow(item)][toCol(item)]=1
          selectPos.value=0
          score.value--
          let ret=wolfAi.wolfStep(board.value)
          if (ret==null){
            gameOver(1)
            return
          }
          //如果当前位置有白棋，且是选中状态
          if (ret[toRow(item)][toCol(item)]==2){
            //将焦点移动到其他白子
            console.log('焦点将丢失')
            let itemPos=wolfAi.itemsChar(board.value,1)[0]
            if(itemPos){
              let newIndex=toIndex(itemPos.x,itemPos.y)
              console.log('newIndex:',newIndex)
              boardItem.value[newIndex].requestFocus()
            }
          }
          board.value=ret
          if (selectList.value.length==0){
            gameOver(0)
            return
          }
        }
      }
    }
    function gameOver(winner){
      if (isPlaying.value) {
        isPlaying.value = false
        emit('gameStateChange',isPlaying.value)
        let msg=''
        if(winner==1){
          msg="您赢了!"
        }else{
          msg="您输了!"
        }
        if (winner==1){
          saveScore(score.value)
        }
        router.push({
          name: 'game_over_view',
          params: {
            status: false,
            message: msg+'您的步数是：' + (-score.value)
          }
        })
      }
    }
    function toRow(item){
      return cached((e)=>Math.floor((e-1)/5))(item)
    }
    function toCol(item) {
      return cached((e)=>(e-1)%5)(item)
    }
    function toIndex(x,y){
      return cached2n((e1,e2)=>(e1*5+e2))(x,y)
    }
    function itemStyle(item){
      let row=toRow(item)
      let col=toCol(item)
      let selectColor='#f59e0b'
      let itemValue=board.value[row][col]
      let defaultBackgroundColor=colorMap[itemValue]
      let borderColor='transparent'
      let focusBorderColor='transparent'
      let focusBackgroundColor=defaultBackgroundColor
      if (item==selectPos.value){
        borderColor=selectColor
        focusBorderColor=selectColor
      }
      if (itemValue==0){
        focusBorderColor=selectColor
        focusBackgroundColor=selectColor
      }
      return {
        backgroundColor:defaultBackgroundColor,
        focusBorderColor:focusBorderColor,
        borderColor:borderColor,
        top:row*180+8,
        left:col*180+8,
        focusBackgroundColor: focusBackgroundColor
      }
    }
    function itemFocusable(item){
      return isPlaying.value&&selectList.value.indexOf(item-1)!=-1
    }
    function requestFocus(){
      console.log('requestFocus')
      startBtn.value.requestFocus()
    }
    return {
      score,
      init,
      isPlaying,
      onBackPressed,
      rankList,
      meRank,
      loginInit,
      board,
      placeStone,
      colorMap,
      boardItem,
      selectList,
      itemStyle,
      itemFocusable,
      guize,
      getRankList,
      getMeRank,
      requestFocus,
      startBtn
    }
  }
})
</script>


<style scoped>

.score {
  font-size: 32px;
  margin: 20px;
  width: 200px;
  text-align: left;
}

.layout {
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  width: 900px;
  height: 980px;
}

.layout .all-container {
  height: 840px;
  width: 840px;
  display:flex;
  justify-content: center;
  align-items: center;
}

.leftContent {
  width: 510px;
  height: 900px;

}
.guize-title{
  width: 510px;
  height: 60px;
  padding-left: 20px;
  font-size: 32px;
}
.guize-content{
  width: 510px;
  height: 800px;
  padding-left: 20px;
  font-size: 28px;
}

.ranklist {
  width: 510px;
  height: 900px;
}

.meRank {
  width: 260px;
  text-align: center;
  font-size: 32px;
}

.board {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 800px;
  height: 800px;
  border-width: 1px;
  border-color: black;
  background-color: #bbada0
}
.board-row{
  display:flex;
  flex-direction: row;
}
.board-col{
  width: 180px;
  height: 180px;
  border-width: 1px;
  border-color: black;
  background-color: transparent;
}
.board-item{
  position: absolute;
  width: 60px;
  height: 60px;
  border-radius: 30px;
  border-width: 8px;
  focus-border-radius:30px;
}
</style>
